<template>
	<el-dialog
		:title="title"
		:visible.sync="dialogVisible"
		:append-to-body="true"
		width="65%"
		top="6.5vh"
		custom-class="img-edit"
		:close-on-click-modal="false"
	>
		<el-upload
			class="goods__upload"
			action="https://jsonplaceholder.typicode.com/posts/"
			:auto-upload="false"
			:limit="1"
			:file-list="fileList"
			:show-file-list="false"
			:on-change="changeFile"
		>
			<el-button size="mini" type="primary">选取图片</el-button>
		</el-upload>
		<vue-cropper
			ref="cropper"
			:img="targetFile"
			:full="false"
			:center-box="false"
			:can-move="true"
			:auto-crop="true"
			mode="auto"
			enlarge="5"
		></vue-cropper>
		<span slot="footer" class="dialog-footer">
	    <el-button
		    @click="dialogVisible = false"
		    size="mini"
	    >
		    取 消
	    </el-button>
	    <el-button
		    type="primary"
		    size="mini"
		    :disabled="disabled"
		    @click="ensure">
		    确 定
	    </el-button>
	  </span>
	</el-dialog>
</template>

<script>
  /**
   *
   *
   *
   */
  import {VueCropper} from 'vue-cropper/src/index'

  export default {
    name: "img-edit",
    props: ['title'],
    data() {
      return {
        dialogVisible: false,
        fileList: [],
        targetFile: null
      }
    },
    computed: {
      disabled() {
        return this.targetFile === null
      }
    },
    watch: {
      fileList: {
        deep: true,
        async handler() {
          let targetFile = null,
            fileList = this.fileList
          if (fileList.length > 0) {
            await new Promise(resolve => {
              let temp = fileList[0].raw
              let reader = new FileReader();
              reader.onload = (e) => {
                targetFile = e.target.result
                resolve()
              }
              reader.onerror = () => {
                resolve()
              }
              reader.readAsDataURL(temp)
            })
          }
          this.targetFile = targetFile
        }
      }
    },
    mounted() {
      this.$bus.$on('goods-img__edit', () => {
        this.fileList = []
        this.dialogVisible = true
      })
    },
    methods: {
      changeFile(file, fileList) {
        this.fileList = fileList
      },
      ensure() {
        this.$refs.cropper.getCropData((data) => {
          this.$emit('submit', data)
          this.dialogVisible = false
        })
      }
    },
    components: {
      VueCropper
    }
  }
</script>

<style lang='less'>
	.img-edit {
		.goods__upload {
			padding: 0 0 20px 0;
		}

		.vue-cropper {
			width: 100%;
			height: 480px;
		}
	}
</style>
